package com.question.dao.daoFactory;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.util.Properties;

import com.question.dao.AcademyDao;
import com.question.dao.StudentDao;
import com.question.dao.TopicDao;

//单例模式
public class DaoFactory {
	private static StudentDao studentDao = null;
	private static TopicDao topicDao = null;
	private static AcademyDao academyDao = null;
	
	//返回唯一一个实例
	private static DaoFactory instance = new DaoFactory();

	private DaoFactory() {
		Properties properties = new Properties();
		InputStream is = null;
		String studentDaoClass = null;
		String topicDaoClass = null;
		String academyDaoClass = null;

		try {
			is = DaoFactory.class.getClassLoader().getResourceAsStream("daoFactory.properties");
			properties.load(is);

			studentDaoClass = properties.getProperty("studentDao");
			topicDaoClass = properties.getProperty("topicDao");
			academyDaoClass = properties.getProperty("academyDao");

			try {
				Class<StudentDao> class1 = (Class<StudentDao>) Class.forName(studentDaoClass);
				Constructor<StudentDao> con = class1.getDeclaredConstructor();
				studentDao = con.newInstance();

				Class<TopicDao> class2 = (Class<TopicDao>) Class.forName(topicDaoClass);
				Constructor<TopicDao> con2 = class2.getDeclaredConstructor();
				topicDao = con2.newInstance();
				
				Class<AcademyDao> class3 = (Class<AcademyDao>) Class.forName(academyDaoClass);
				Constructor<AcademyDao> con3 = class3.getDeclaredConstructor();
				academyDao = con3.newInstance();

			} catch (Exception e) {
				throw new RuntimeException(e);
			}

		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public StudentDao getStudentDao() {
		return studentDao;
	}

	public TopicDao geTopicDao() {
		return topicDao;
	}
	
	public AcademyDao getAcademyDao(){
		return academyDao;
	}
	
	public static DaoFactory getInstance() {
		return instance;
	}
}
